//
//  RecommendDetailViewController.m
//  糗事百科
//
//  Created by 奚超明 on 16/6/2.
//  Copyright © 2016年 奚超明. All rights reserved.
//

#import "RecommendDetailViewController.h"
#import "CrossModel.h"
#import "RecommendModel.h"
#import "CrossCell.h"
#import "RecommendCell.h"
#import "RecommendView.h"

#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface RecommendDetailViewController () <UITableViewDelegate, UITableViewDataSource>
/** tableview */
@property (nonatomic, weak) UITableView *tableView;
/** 评论数组 */
@property (nonatomic, strong) NSMutableArray *modelArr;
/** 当前页码 */
@property (nonatomic, assign) NSInteger page;
/** 当前请求 */
@property (nonatomic, weak) NSMutableDictionary *parameters;
/** 输入评论界面 */
@property (nonatomic, weak) RecommendView *recommendView;
/** 记录键盘弹出还是收回 */
@property (nonatomic, assign, getter=isKeyboardShow) BOOL keyboardShow;

@end

@implementation RecommendDetailViewController

static NSString * const recommendID = @"recommend";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 界面初始化
    [self setupView];
    
    // 添加刷新控件
    [self addRefresh];
}

#pragma mark - 界面初始化
- (void)setupView
{
    // 标题
    self.navigationItem.title = [NSString stringWithFormat:@"糗事:%@", self.model.ID];
    
    // tableview
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([RecommendCell class]) bundle:nil] forCellReuseIdentifier:recommendID];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CrossCell class]) bundle:nil] forCellReuseIdentifier:@"cross"];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView = tableView;
    [self.view addSubview:tableView];
    
    // 添加输入评论界面
    RecommendView *recommendView = [[RecommendView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 40, [UIScreen mainScreen].bounds.size.width, 40) target:self expressionAction:@selector(expressionAction:) enterAction:@selector(enterAction:)];
    __weak RecommendView *block = recommendView;
    recommendView.block = ^(CGFloat textViewH) {
        // 评论框初始高度
        CGFloat beginH = block.xcm_height;
        
        // 评论框改变后的高度
        block.xcm_height = textViewH + kMargin;
        
        // 评论框高度改变的差值
        CGFloat delta = beginH - block.xcm_height;
        
        // 改变评论框的y值
        block.xcm_y += delta;
    };
    [self.view addSubview:recommendView];
    self.recommendView = recommendView;
    
    // 监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    // 记录键盘状态是未弹出
    self.keyboardShow = NO;
}

#pragma mark - 表情
- (void)expressionAction:(UIButton *)sender
{
    
}

#pragma mark - 发表评论
- (void)enterAction:(UIButton *)sender
{
    // 收回键盘
    [self.recommendView.textView resignFirstResponder];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"发表成功" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *enterAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:enterAction];
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });
}

#pragma mark - 键盘弹出及收回
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 键盘frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 键盘变化的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        
    // 如果键盘弹出状态，就return
    if (self.keyboardShow && kScreenHeight - frame.size.height == frame.origin.y) {
        return;
    }
    
    // 判断键盘弹出还是收回状态
    if (kScreenHeight - frame.size.height == frame.origin.y) { // 键盘弹出状态
        [UIView animateWithDuration:duration animations:^{
            self.recommendView.xcm_y -= frame.size.height;
            
            // 记录登录状态
            self.keyboardShow = YES;
        }];
    } else { // 键盘收回状态
        [UIView animateWithDuration:duration animations:^{
            self.recommendView.xcm_y += frame.size.height;
            
            // 记录登录状态
            self.keyboardShow = NO;
        }];
    }
}

#pragma mark - 监听结束，销毁通知
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 添加刷新控件
- (void)addRefresh
{
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 一进入就刷新
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - 加载新数据
- (void)loadNewData
{
    // 停止上拉刷新
    [self.tableView.mj_footer endRefreshing];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"article"] = @"1";
    parameters[@"count"] = @"50";
    parameters[@"page"] = @"1";
    self.parameters = parameters;
    
    [[AFHTTPSessionManager manager] GET:[NSString stringWithFormat:@"http://m2.qiushibaike.com/article/%@/latest/comments", self.model.ID] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.parameters != parameters) {
            return;
        }
        
        // 改变页码
        self.page = 1;
        
        // 清除所有数据
        [self.modelArr removeAllObjects];
        
        NSDictionary *rootDic = responseObject;
        NSArray *itemsArr = rootDic[@"items"];
        for (NSDictionary *recommendDic in itemsArr) {
            RecommendModel *model = [RecommendModel recommendWithDic:recommendDic];
            [self.modelArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
            if (self.modelArr.count >= [rootDic[@"total"] integerValue]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError];
    }];
}

#pragma mark - 加载更多数据
- (void)loadMoreData
{
    
    // 停止下拉刷新
    [self.tableView.mj_header endRefreshing];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"article"] = @"1";
    parameters[@"count"] = @"50";
    parameters[@"page"] = [NSString stringWithFormat:@"%zd", self.page + 1];
    self.parameters = parameters;
    
    [[AFHTTPSessionManager manager] GET:[NSString stringWithFormat:@"http://m2.qiushibaike.com/article/%@/latest/comments", self.model.ID] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.parameters != parameters) {
            return;
        }
        
        // 改变页码
        self.page++;
        
        NSDictionary *rootDic = responseObject;
        NSArray *itemsArr = rootDic[@"items"];
        for (NSDictionary *recommendDic in itemsArr) {
            RecommendModel *model = [RecommendModel recommendWithDic:recommendDic];
            [self.modelArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            
            if (self.modelArr.count >= [rootDic[@"total"] integerValue]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableView.mj_footer endRefreshing];
            }
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError];
    }];
}

#pragma mark - 显示错误信息
- (void)showError
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"亲，您的网络有问题！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:confirmAction];
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });
}

#pragma mark - 判断上拉控件的隐藏于显示
- (void)judgeFooterRefreshShowOrHidden
{
    if (self.modelArr.count == 0) {
        self.tableView.mj_footer.hidden = YES;
    } else {
        self.tableView.mj_footer.hidden = NO;
    }
}

#pragma mark - 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [self judgeFooterRefreshShowOrHidden];
    return self.modelArr.count + 1;
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        CrossCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cross"];
        cell.model = self.model;
        return cell;
    } else {
        RecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:recommendID];
        cell.model = self.modelArr[indexPath.row - 1];
        return cell;
    }
}

#pragma mark - 返回行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return self.model.cellHeight;
    } else {
        tableView.estimatedRowHeight = 200;
        return UITableViewAutomaticDimension;
    }
}

#pragma mark - 拖动界面收回键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.recommendView.textView resignFirstResponder];
}

#pragma mark - 懒加载
- (NSMutableArray *)modelArr
{
    if (!_modelArr) {
        _modelArr = [NSMutableArray array];
    }
    return _modelArr;
}

@end
